//
//  AdoptedNewPayViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/5.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "AdoptedNewPayViewController.h"
#import "MeatPaySuccessViewController.h"
#import "PayResultViewController.h"
#import "TopUpViewController.h"

#import "AdoptedPayPigDetailsCell.h"

#import "MeatPayOrderModel.h"
#import "MeatPayView.h"

@interface AdoptedNewPayViewController ()

@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, strong) MeatPayView *footer;
@property (nonatomic, strong) NSArray *icons;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) UITextField *textField; //
@property (nonatomic, strong) MeatOrderModel *orderModel;
@property (nonatomic, strong) UITableViewCell *aimCell;
@property (nonatomic, copy) NSString *payType;
@property (nonatomic, copy) NSString *resetMoney;
@property (nonatomic, strong) NSString *ordernum;

@end

@implementation AdoptedNewPayViewController


- (void)setupUI{
    
    self.baseNavView.navTitleLabel.text = @"支付";
    self.baseNavView.line.hidden = YES;
    self.aimCell = nil;
    self.resetMoney = @"0";
    [self addkeyBoardNotification];
    [self.view addSubview:self.footer];
}


- (void)setupLayout{
    
    self.tableView.mj_y = TJ_NavBarHeight;
    self.tableView.height = KScreenHeight - ( _footer.height +TJ_NavBarHeight);
    _footer.mj_y = self.tableView.bottom ;
}


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self balanceRequest];
}


#pragma mark - networking methods

- (void)initData{
    
}

- (void)topUpRequestWithPayType:(PayType)payType{
    
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;
    TopUpMoneyParam *param = [[TopUpMoneyParam alloc] init];
    
    param.payType = @(payType);
    //param.payType = @(1); //余额支付

    param.pigId = pigId;
    param.memberId = kMemberId;
    param.money = @"0.01";
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] topUpRequestWithParam:param] subscribeNext:^(Pay * _Nullable pay) {
        
        @strongify(self);
        switch (payType) {
            case PayTypeWechat:
            {
                //调取微信SDK
                [self thirdTopUpWithPayModel:pay];
                
            }
                break;
            case PayTypeAlipay:
            {
                //调取支付宝SDK
                [self alipayTopUpWithModel:pay];
            }
                break;
            default:
                break;
        }
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//调取微信SDK
- (void)thirdTopUpWithPayModel:(Pay *)payModel{
    
    //调取微信支付SDK
    @weakify(self);
    [[PayManager sharedManager] payWithWeChatMethod:payModel callBack:^(PayErrCode errCode, NSString *errStr) {
        @strongify(self);
        if (errCode == PayErrCodeSuccess) {//成功 调取本地接口
            [self toastWithContent:@"充值成功"];
            //刷新余额
            [self balanceRequest];
            
        } else {
            [self toastWithContent:errStr];
        }
    }];
}


//支付宝充值
- (void)alipayTopUpWithModel:(Pay *)model {
    //调取支付宝支付SDK
    @weakify(self);
    [[PayManager sharedManager] payWithAlipayMethod:model.orderNum callBack:^(PayErrCode errCode, NSString *errStr) {
        if (errCode == PayErrCodeSuccess) {
            @strongify(self);
            [self toastWithContent:@"充值成功"];
            //刷新余额
            [self balanceRequest];
            
        } else {
            @strongify(self);
            [self toastWithContent:errStr];
        }
    }];
}


#pragma mark - 支付
//支付
- (void)payRequestWithPayPassword:(NSString *)password withPayType:(NSNumber *)payType{
    
    AdoptedPayParam *param = [[AdoptedPayParam alloc] init];
    param.adoptPlanId = self.adoptPlanId;
    param.payableMoney = self.owedPaymentMoney;//应付钱数
    param.adoptMoney = self.owedPaymentMoney;//实付钱数
    param.payType = payType;
    param.trustDetailIds = self.trusteeIdArr;
    param.pigCouponIds = @[];
    param.payPwd = password;

    @weakify(self);
    [[[PigMarketApi sharedInstance] adoptedPayWithParam:param] subscribeNext:^(Pay * _Nullable pay) {
        
        //订单编号
        self.ordernum = pay.ordernum;
        @strongify(self);
        if ([payType intValue] == 1) {//余额支付
            
            [[PayInputView sharedInstance] unDisplay];
            
            [self pushPayResultVCWithModel:pay];
            
        } else if ([payType intValue] == 2) {//支付宝
            
            [self alipayWithPayModel:pay];
            
        } else if ([payType intValue] == 3) {//微信
            //调取sdk支付
            [self wxPayWithPayModel:pay];
        }
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
        [self showHudWithMsg:@"支付失败"];
        [[PayInputView sharedInstance] unDisplay];
    }];
}


//调取微信支付SDK
- (void)wxPayWithPayModel:(Pay *)payModel{
    
    //调取微信支付SDK
    @weakify(self);
    [[PayManager sharedManager] payWithWeChatMethod:payModel callBack:^(PayErrCode errCode, NSString *errStr) {
        @strongify(self);
        if (errCode == PayErrCodeSuccess) {//成功 调取本地接口
            [self pushPayResultVCWithModel:payModel];
        } else {
            [self toastWithContent:errStr];
        }
    }];
}


//调取支付宝支付SDK
- (void)alipayWithPayModel:(Pay *)payModel {
    //调取支付宝支付SDK
    NSString *orderStr = payModel.payRequest;
    [[PayManager sharedManager] payWithAlipayMethod:orderStr callBack:^(PayErrCode errCode, NSString *errStr) {
        if (errCode == PayErrCodeSuccess) {
            [self pushPayResultVCWithModel:payModel];
        } else {
            [self toastWithContent:errStr];
        }
    }];
}


#pragma mark - 获取余额
//获取余额
- (void)balanceRequest {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    
    [[[PigMarketApi sharedInstance] getBalanceWithMemberId:memberId] subscribeNext:^(Pay * _Nullable pay) {
        @strongify(self);
        
        [kUserDefaults setObject:pay.balance forKey:kUserPrice];
        [kUserDefaults synchronize];
        NSString *price = [NSString stringWithFormat:@"可用余额%@元", [kUserDefaults stringForKey:kUserPrice]];
        self.titles = @[@[@"微信支付", @"支付宝"],  @[@"余额支付", @"¥", price], @[@"微信好友代付"]];
        
        [self localReloadTableViewBySection:2];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//跳到支付成功页面
- (void)pushPayResultVCWithModel:(Pay *)model {
    PayResultViewController *resultVC = [[PayResultViewController alloc] init];
    resultVC.model = model;
    resultVC.actuallyPaymentMoney = self.actuallyPaymentMoney;
    [self.navigationController pushViewController:resultVC animated:YES];
}


#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger row = 1;
    if (section == 1) {
        row = 3;
    }else if (section == 2){
        return row = 4;
    }else if (section == 3){
        return 2;
    }
    return row;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) return 100;
    return indexPath.row == 0 ?32 : 54;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath .section == 0) {
        
        AdoptedPayPigDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AdoptedPayPigDetailsCell"];

        [cell.pigIcon sd_setImageWithURL:[NSURL URLWithString:self.model.headImg] placeholderImage:[UIImage imageNamed:@"placeholder_small"]];
        cell.pigNameLab.text = self.model.varieties;
        cell.pigNumLab.text = [NSString stringWithFormat:@"编号%@",self.model.pigNum];
        cell.priceLab.text = [NSString stringWithFormat:@"￥%@",self.owedPaymentMoney];

        return cell;
    }
    
    
    UITableViewCell *newsCell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    newsCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!newsCell) {
        newsCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"];
    }
    newsCell.textLabel.font = mFont(15);
    
    if (indexPath.row != 0) {
        
        newsCell.accessoryView = ({
            UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"meat_cart_unchecked"]];
            CGRect frame = imgV.frame;
            frame.size = CGSizeMake(18, 18);
            imgV.frame = frame;
            [imgV setContentMode:UIViewContentModeLeft];
            imgV;
        });
    }
    
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {
            newsCell.textLabel.text = @"第三方支付方式";
            newsCell.textLabel.textColor = UIColorFromRGB(0x969696);
            newsCell.backgroundColor = mBackgroudColor;
            newsCell.textLabel.font = mFont(14);
            
            if ([newsCell respondsToSelector:@selector(setSeparatorInset:)]) {
                [newsCell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
            
        }else{
            
            newsCell.textLabel.textColor = UIColorFromRGB(0x333333);
            newsCell.textLabel.text = self.titles[0][indexPath.row - 1];
            newsCell.imageView.image = [UIImage imageNamed:self.icons[0][indexPath.row - 1]];
        }
    }
    
    if (indexPath.section == 2) {
        
        if (indexPath.row == 0) {
            newsCell.textLabel.text = @"账户支付";
            newsCell.textLabel.textColor = UIColorFromRGB(0x969696);
            newsCell.textLabel.font = mFont(14);
            newsCell.backgroundColor = mBackgroudColor;
            
            if ([newsCell respondsToSelector:@selector(setSeparatorInset:)]) {
                [newsCell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
            
        }else{
            
            newsCell.textLabel.textColor = indexPath.row == 3 ?UIColorFromRGB(0x999999) :UIColorFromRGB(0x333333);
            newsCell.textLabel.font = indexPath.row == 3 ?mFont(12) :mFont(15);
            
            newsCell.textLabel.text = self.titles[1][indexPath.row - 1];
            newsCell.imageView.image = [UIImage imageNamed:self.icons[1][indexPath.row - 1]];
            newsCell.imageView.hidden = indexPath.row == 1? NO :YES;
            newsCell.accessoryView.hidden = indexPath.row != 3 ?NO :YES;
            
            
            if (indexPath.row == 2) {
                
                [newsCell addSubview:self.textField];
                newsCell.accessoryView = ({
                    UIButton *button = [UIButton makeButtonWithText:@"去充值" textColor:mMainColor font:mFont(12) textAliment:1 cornerRadius:5];
                    button.layer.borderWidth = 1;
                    button.layer.borderColor = mMainColor.CGColor;
                    CGRect frame = button.frame;
                    frame.size = CGSizeMake(56, 27);
                    button.frame = frame;
                    [button setContentMode:UIViewContentModeLeft];
                    
                    @weakify(self);
                    button.tapBlock = ^{
                        @strongify(self);
                        
                        float price = [self.resetMoney floatValue];
                        if (price <=0) {
                            [self showHudWithMsg:@"请输入充值金额"];
                            return;
                        }
                        
                        TopUpViewController *vc = [[TopUpViewController alloc] init];
                        vc.price = self.resetMoney;
                        [self.navigationController pushViewController:vc animated:YES];
                        
                    };
                    button;
                });
            }
        }
    }
    
    if (indexPath.section == 3) {
        
        if (indexPath.row == 0) {
            newsCell.textLabel.text = @"朋友代付";
            newsCell.textLabel.textColor = UIColorFromRGB(0x969696);
            newsCell.backgroundColor = mBackgroudColor;
            newsCell.textLabel.font = mFont(14);
            
            
            if ([newsCell respondsToSelector:@selector(setSeparatorInset:)]) {
                [newsCell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
            
        }else{
            
            newsCell.textLabel.textColor = UIColorFromRGB(0x333333);
            newsCell.textLabel.text = self.titles[2][indexPath.row - 1];
            newsCell.imageView.image = [UIImage imageNamed:self.icons[2][indexPath.row - 1]];
        }
    }
    
    return newsCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    BOOL checked = (indexPath.section == 2 &&indexPath.row == 3) ||(indexPath.section == 2 && indexPath.row == 2);
    
    if (!checked){
        
        UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
        if (cell.accessoryView && !cell.accessoryView.hidden) {
            cell.accessoryView = ({
                UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"meat_pay_choosed"]];
                CGRect frame = imgV.frame;
                frame.size = CGSizeMake(18, 18);
                imgV.frame = frame;
                [imgV setContentMode:UIViewContentModeLeft];
                imgV;
            });
        }
        
        if (self.aimCell == nil) {
            self.aimCell = cell;
        }else{
            
            self.aimCell.accessoryView = ({
                UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"meat_cart_unchecked"]];
                CGRect frame = imgV.frame;
                frame.size = CGSizeMake(18, 18);
                imgV.frame = frame;
                [imgV setContentMode:UIViewContentModeLeft];
                imgV;
            });
            self.aimCell = cell;
        }
        
        switch (indexPath.section) {
            case 1:
            {
                self.payType = indexPath.row == 1? @"3":@"2";
            }
                break;
            case 2:
            {
                self.payType = @"1";
            }
                break;
            default:
                break;
        }
        
        if (indexPath.section == 3) {
            [self showHudWithMsg:@"朋友代付"];
        }
    }
}


#pragma mark - setter and getter

#pragma mark - override methods

- (void)registerTableViewCell{
    
    self.tableView.height = KScreenHeight - (TJ_NavBarHeight);
    self.tableView.mj_y = self.baseNavView.bottom;
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.mj_footer = nil;
    self.tableView.mj_header = nil;
    [self.tableView registerClass:[AdoptedPayPigDetailsCell class] forCellReuseIdentifier:@"AdoptedPayPigDetailsCell"];
}


- (NSMutableAttributedString *)getPayText:(NSString *)text{
    
    NSString *payTipS = @"实付款：";
    NSString *moneySymbol = @"¥";
    NSString *totalS = [NSString stringWithFormat:@"%@%@%@", payTipS, moneySymbol, text];
    
    NSMutableAttributedString *attributedS = [[NSMutableAttributedString alloc] initWithString:totalS];
    
    [attributedS addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x5E5E5E) range:NSMakeRange(0, 4)];
    [attributedS addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xF25C62) range:NSMakeRange(4, totalS.length -4)];
    [attributedS addAttribute:NSFontAttributeName value:mFont(13) range:NSMakeRange(0, 4)];
    [attributedS addAttribute:NSFontAttributeName value:mFont(12) range:NSMakeRange(4, 1)];
    [attributedS addAttribute:NSFontAttributeName value:mMediumFont(17) range:NSMakeRange(5, totalS.length - 5)];
    
    return attributedS;
}



- (MeatPayView *)footer{
    if (!_footer) {
        _footer = [[MeatPayView alloc] init];
        _footer.type = MeatPayType_Submit;
        [_footer.payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [_footer.payDetailLab setText:[NSString stringWithFormat:@"（已优惠%@元）", self.discountMoney]];
        
        NSMutableAttributedString *aims = [self getPayText:self.owedPaymentMoney];
        _footer.payLab.attributedText = aims;
//        _footer.hidden = YES;
        
        //支付Block
        @weakify(self);
        _footer.payCartBlock = ^{
            @strongify(self);

            if ([self.payType integerValue] == 3) {
                //微信支付
                [self payRequestWithPayPassword:@"" withPayType:@3];
            } else if ([self.payType integerValue] == 2) {

                [self payRequestWithPayPassword:@"" withPayType:@2];
            } else if ([self.payType integerValue] == 1) {
                //支付密页面
                @weakify(self);
                [[PayInputView sharedInstance] display];
                [[PayInputView sharedInstance] setInputCompleteBlock:^(SecureTextEntryView * _Nonnull secureView) {
                    @strongify(self);
                    [self payRequestWithPayPassword:secureView.text withPayType:@1];
                }];
            } else {
                return;
            }
       };
            
        
    }
    return _footer;
}



- (UITextField *)textField {
    
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.placeholder = @"本次充值最多可以充值多少元";
        _textField.font = mFont(12);
        _textField.size = CGSizeMake(200, 54);
        _textField.mj_x = 70;
        _textField.mj_y = 0;
        _textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _textField;
}


- (NSArray *)icons{
    
    if (!_icons) {
        _icons = @[@[@"meat_pay_alipay", @"meat_pay_wechat"],  @[@"meat_pay_yue", @"meat_pay_yue", @"meat_pay_yue"], @[@"meat_friend_pay"]];
    }
    return _icons;
}


- (NSArray *)titles{
    
    if (!_titles) {
        
        NSString *price = [NSString stringWithFormat:@"可用余额%@元", [kUserDefaults stringForKey:kUserPrice]];
        _titles = @[@[@"微信支付", @"支付宝"],  @[@"余额支付", @"¥", price], @[@"微信好友代付"]];
    }
    return _titles;
}


- (MeatOrderModel *)orderModel{
    
    if (!_orderModel) {
        _orderModel = [[MeatOrderModel alloc] init];
    }
    return _orderModel;
}


#pragma mark - notification methods

- (void)textFieldTextChanged:(NSNotification *)notification
{
    UITextField *textField = notification.object;
    self.resetMoney = textField.text;
}

- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    kWeakSelf(self);
    [UIView animateWithDuration:duration animations:^{
        weakself.tableView.mj_y = 0;
    }];
    
    //当键盘升起的时候添加点击降落操作
    if (!self.tap) {
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    }
    [self.view addGestureRecognizer:self.tap];
}

//取消键盘响应
- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}


- (void)keyboardWillHide:(NSNotification *)notification{
    
    self.tableView.mj_y = TJ_NavBarHeight;
    if (self.tap) {
        [self.view removeGestureRecognizer:self.tap];
    }
}


//添加键盘通知
- (void)addkeyBoardNotification{
    
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

//移除键盘通知
- (void)removeKeyboardNotification{
    
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc{
    
    [self removeKeyboardNotification];
}


@end
